package com.ym.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * Description
 * Created by 王伟
 * Date create on 21:40 2018/6/20.
 */
@Aspect
@Component
@Order(Ordered.LOWEST_PRECEDENCE-1)
public class DataSourceContract {
    @Pointcut("@annotation(com.ym.datasource.UseDataSource)")
    private void anyMethod(){}//定义一个切入点,所有注解了UseDataSource的方法或类

    @Around("anyMethod() && @annotation(anno)")
    public Object dataSourceSwitcher(ProceedingJoinPoint joinPoint, UseDataSource anno) throws Throwable {
        String dataSource;
        DataSourceType value = anno.value();
        dataSource = value.getSource();
        DataSourceContextHolder.setDataSourceType(dataSource);
        System.out.println("当前使用的数据源为"+value.getDesc());
        try {
            //执行方法
            Object result = joinPoint.proceed();
            return result;
        }catch (Exception e){
            throw e;
        }finally {
            //切换回原来的数据源（重要）
            if(!dataSource.equals(DataSourceType.SOURCE_1.getSource()))
                DataSourceContextHolder.setDataSourceType(DataSourceType.SOURCE_1.getSource());
            System.out.println("切换回默认数据源为"+DataSourceType.SOURCE_1.getDesc());
        }
    }

}
